package com.ruoyi.web.controller.net;

import com.ruoyi.net.domain.ElementSrNeighb;
import com.ruoyi.net.domain.NetElement;
import com.ruoyi.net.netconf.util.DeviceManager;
import com.ruoyi.net.service.INetElementService;
import com.ruoyi.system.service.ISysConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.net.domain.ElementSrLabel;
import com.ruoyi.net.service.IElementSrLabelService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 网元-SR-全局标签范围Controller
 * 
 * @author net
 * @date 2024-11-17
 */
@Api(tags = "网元-SR-全局标签范围")
@RestController
@RequestMapping("/element/sr/label")
public class ElementSrLabelController extends BaseController {
    @Autowired
    private IElementSrLabelService elementSrLabelService;

    @Autowired
    private INetElementService netElementService;

    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    private DeviceManager deviceManager;

    /**
     * 读取网元-SR-全局标签范围列表
     */
    @ApiOperation(value = "读取网元-SR-全局标签范围列表", httpMethod = "GET")
    //    @PreAuthorize("@ss.hasPermi('system:label:list')")
    @GetMapping("/read")
    public TableDataInfo read(ElementSrLabel elementSrLabel) {
        startPage();
        List<ElementSrLabel> list = new ArrayList<>();
        return getDIYPageTable(list);
    }

    /**
     * 查询网元-SR-全局标签范围列表
     */
    @ApiOperation(value = "查询网元-SR-全局标签范围列表", httpMethod = "GET")
    //    @PreAuthorize("@ss.hasPermi('system:label:list')")
    @GetMapping("/list")
    public TableDataInfo list(ElementSrLabel elementSrLabel) {
        startPage();
        List<ElementSrLabel> list = elementSrLabelService.selectElementSrLabelList(elementSrLabel);
        return getDataTable(list);
    }

    /**
     * 导出网元-SR-全局标签范围列表
     */
    @ApiOperation(value = "导出网元-SR-全局标签范围列表", httpMethod = "POST")
    //    @PreAuthorize("@ss.hasPermi('system:label:export')")
    @Log(title = "网元-SR-全局标签范围", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ElementSrLabel elementSrLabel) {
        List<ElementSrLabel> list = elementSrLabelService.selectElementSrLabelList(elementSrLabel);
        ExcelUtil<ElementSrLabel> util = new ExcelUtil<ElementSrLabel>(ElementSrLabel.class);
        util.exportExcel(response, list, "网元-SR-全局标签范围数据");
    }

    /**
     * 获取网元-SR-全局标签范围详细信息
     */
    @ApiOperation(value = "获取网元-SR-全局标签范围详细信息", httpMethod = "GET")
    //    @PreAuthorize("@ss.hasPermi('system:label:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return success(elementSrLabelService.selectElementSrLabelById(id));
    }

    /**
     * 新增网元-SR-全局标签范围
     */
    @ApiOperation(value = "新增网元-SR-全局标签范围", httpMethod = "POST")
    //    @PreAuthorize("@ss.hasPermi('system:label:add')")
    @Log(title = "网元-SR-全局标签范围", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ElementSrLabel elementSrLabel) {
        return toAjax(elementSrLabelService.insertElementSrLabel(elementSrLabel));
    }

    /**
     * 修改网元-SR-全局标签范围
     */
    @ApiOperation(value = "修改网元-SR-全局标签范围", httpMethod = "PUT")
    //    @PreAuthorize("@ss.hasPermi('system:label:edit')")
    @Log(title = "网元-SR-全局标签范围", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ElementSrLabel elementSrLabel) {
        return toAjax(elementSrLabelService.updateElementSrLabel(elementSrLabel));
    }

    /**
     * 删除网元-SR-全局标签范围
     */
    @ApiOperation(value = "删除网元-SR-全局标签范围", httpMethod = "DELETE")
    //    @PreAuthorize("@ss.hasPermi('system:label:remove')")
    @Log(title = "网元-SR-全局标签范围", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(elementSrLabelService.deleteElementSrLabelByIds(ids));
    }


    @ApiOperation(value = "删除网元-SR-全局标签范围(单个）", httpMethod = "DELETE")
    //    @PreAuthorize("@ss.hasPermi('system:label:remove')")
    @Log(title = "网元-SR-全局标签范围", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public AjaxResult removeById(@PathVariable String id) {

        return toAjax(elementSrLabelService.deleteElementSrLabelById(id));
    }
    /**
     * 激活设备
     * @param id
     */
    @ApiOperation(value = "激活设备", httpMethod = "GET")
    @Log(title = "激活设备", businessType = BusinessType.UPDATE)
    @GetMapping(value = "/activate/{id}")
    public AjaxResult activateDevice(@PathVariable("id") String id) {
        ElementSrLabel entity = elementSrLabelService.selectElementSrLabelById(id);
        entity.setStatus("1");
        if (sendXml(entity)){
            return toAjax(elementSrLabelService.updateElementSrLabel(entity));
        }else {
            return AjaxResult.error("激活设备失败");
        }
    }

    /**
     * 去激活设备
     * @param id
     */
    @ApiOperation(value = "去激活设备", httpMethod = "GET")
    @Log(title = "去激活设备", businessType = BusinessType.UPDATE)
    @GetMapping(value = "/unactivate/{id}")
    public AjaxResult unactivateDevice(@PathVariable("id") String id) {
        ElementSrLabel entity =  elementSrLabelService.selectElementSrLabelById(id);
        entity.setStatus("0");
        if (sendXml(entity)){
            return toAjax(elementSrLabelService.updateElementSrLabel(entity));
        }else {
            return AjaxResult.error("去激活设备失败");
        }
    }

    /**
     * 发送xml到设备
     *
     * @param entity
     */
    private boolean sendXml(ElementSrLabel entity) {
        boolean isSend = true;
        // TODO: 2024/11/30 设备联调
        if (sysConfigService.selectDebugEnabled()) {
            NetElement netElement = netElementService.getCacheObject(entity.getElementId());
            deviceManager.getDevice(netElement.getIp());
            String operation = "create";
            // 0 未激活
            if ("0".equals(entity.getStatus())) {
                operation = "remove";
            }

            String xml = "<sr xmlns=\"http://fiberhome.com/fhnw/yang/ipprotocol/fos-segmentrouting\">" +
                    "    <srgb nc:operation=\"" + operation + "\">" +
                    "      <lower-bound>" + entity.getStartValue() + "</lower-bound>" +
                    "      <upper-bound>" + entity.getEndValue() + "</upper-bound>" +
                    "    </srgb>" +
                    "  </sr>";

            System.out.println(xml);
            isSend = deviceManager.editConfig(xml, "merge");
        }
        return isSend;
    }
}